package com.ray.service;

import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;

import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.apache.xmlbeans.impl.xb.xsdschema.NarrowMaxMin;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;
import org.springframework.web.multipart.MultipartFile;

import com.google.appengine.api.search.query.QueryParser.restriction_return;
import com.google.appengine.repackaged.com.google.protobuf.proto1api.UInt32Value;
import com.ray.bean.CustomerBean;
import com.ray.bean.DatatablesViewPageBean;
import com.ray.bean.ProcedureBean;
import com.ray.bean.ProcessBean;
import com.ray.bean.QCProcessBean;
import com.ray.bean.QCReportBean;
import com.ray.bean.QCReportDetailBean;
import com.ray.bean.TableData;
import com.ray.bean.UserBean;
import com.ray.exception.ServiceException;
import com.ray.mapper.AttendanceMapper;
import com.ray.mapper.BasicDataMapper;
import com.ray.mapper.ProcedureMapper;
import com.ray.pojo.BaseProcessDetailPojo;
import com.ray.pojo.MyUser;
import com.ray.pojo.attend.AttendPlanAndFinanceDetailPojo;
import com.ray.util.RedirectUrlUtil;
import com.ray.util.ReturnStringUtil;
import com.ray.util.StringUtil;
import com.ray.util.WeiXinParamesUtil;
import com.ray.util.weixin.WeixinTemplateList;
import com.ray.util.weixin.WeixinTemplateSender;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

@Service
public class ProcedureService {

	@Autowired
	ProcedureMapper procedureMapper;
	@Autowired
	BasicDataMapper basicDataMapper;
	@Autowired
	AttendanceMapper attendanceMapper;
	@Autowired
	WeiXinService weiXinService;
	@Autowired
	WeiXinPeopleService weiXinPeopleService;
	@Autowired
	WorkshopService workshopService;
	
	//从工序表获取生产线名称
	public List<String> getProductionLineFromProcess() {
		return procedureMapper.getProductionLineFromProcess();
	}
	
	/**
	 * 通过工序代码更新工序
	 * @param processBean
	 * @param map
	 * @author wangrong
	 * @throws ServiceException 
	 */
	public void updateProcessByCode(ProcessBean processBean,Map<String,Object> map) throws ServiceException {
		Assert.isTrue(processBean.getId()!=null && !"".equals(processBean.getId()),"未获取到工序id");
		List<ProcessBean> list=procedureMapper.getProcessDetail(map);
		if(processBean.getStatus().equals("使用") && list!=null && list.size() >0 ) {
			throw new ServiceException("该工序已存在");
		}
		processBean.setLastModifier(map.get("loginUserName").toString());
		int row=procedureMapper.updateProcessByCode(processBean);
		Assert.isTrue(row>0,"修改失败");
		if(!"0".equals(map.get("isNeedReviewed")) && null!=map.get("isNeedReviewed")) {
			String qcReviewers = map.get("qcReviewers")==null?null:map.get("qcReviewers").toString();
			String reviewers = map.get("reviewers")==null?null:map.get("reviewers").toString();
			JSONArray qcJsonArray = JSONArray.fromObject(qcReviewers);
			JSONArray jsonArray = JSONArray.fromObject(reviewers);
			@SuppressWarnings("unchecked")
			List<Map<String,Object>> qcReviewerList = qcJsonArray.subList(0, qcJsonArray.size());
			List<Map<String,Object>> reviewerList = jsonArray.subList(0, jsonArray.size());
			map.put("qcReviewerList", qcReviewerList);
			map.put("reviewerList", reviewerList);
			basicDataMapper.deleteBaseProcessApprover(map);
			basicDataMapper.insertBaseProcessApprover(map);
		}
	}
	
	//添加工序 wangr  
	public void insertProcess(ProcessBean processBean,Map<String,Object> map) throws ServiceException {
		List<ProcessBean> list=procedureMapper.getProcessDetail(map);
		System.out.println("processList:"+list);
		if(list!=null && list.size() >0) {
			throw new ServiceException("该工序已存在");
		}
		int sort=procedureMapper.getMaxSort()+1;
		processBean.setSortkey(sort);
		//设置工序代码
		processBean.setCompany(map.get("loginCompany").toString());
		processBean.setProcessCode("GXX"+sort);
		processBean.setCreater(map.get("loginUserName").toString());
		procedureMapper.insertProcess(processBean);
		String id = processBean.getId();
		map.put("id", id);
		String reviewers = map.get("reviewers")==null?null:map.get("reviewers").toString();
		String qcReviewers = map.get("qcReviewers")==null?null:map.get("qcReviewers").toString();
		if(reviewers!=null && !reviewers.equals("")) {
			JSONArray jsonArray = JSONArray.fromObject(reviewers);
			@SuppressWarnings("unchecked")
			List<Map<String,Object>> reviewerList = jsonArray.subList(0, jsonArray.size());
			map.put("reviewerList", reviewerList);
			if(qcReviewers != null && !"".equals(qcReviewers)) {
				JSONArray qc = JSONArray.fromObject(qcReviewers);
				List<Map<String,Object>> qcReviewerList = qc.subList(0, qc.size());
				map.put("qcReviewerList", qcReviewerList);
			}
			basicDataMapper.insertBaseProcessApprover(map);
		}
	}
	
	//获取工序详情
	public List<ProcessBean> getProcessDetail(Map map) {
		List<ProcessBean> processDetailBean = procedureMapper.getProcessDetail(map);
		System.out.println("processDetailBean:"+processDetailBean);
		return processDetailBean;
	}
	
	//添加工序
	public void addProcedur(ProcedureBean procedureBean) {
		int sort=procedureMapper.getMaxSort()+1;
		SimpleDateFormat formatter = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
		String dateString = formatter.format(new Date());
		procedureBean.setSortkey(sort);
		procedureBean.setStatus("使用");
		procedureBean.setProcedureNum("GXX"+sort);
		procedureBean.setUpUser(procedureBean.getCreatUser());
		procedureBean.setCreatTime(dateString);
		procedureBean.setUpTime(dateString);
		System.out.println(procedureBean.getSort());
		procedureMapper.insertProcedure(procedureBean);
	}

	public boolean checkWorkShop(String workShop) {
		int count=procedureMapper.getWorkShopCount(workShop);
		if(count>0) {
			return true;
		}
		return false;
	}

	public void updateAllProcessByCode(String beanArray, Map<String,Object> map) throws ServiceException {
		JSONArray jsonArray = JSONArray.fromObject(beanArray);//把String转换为 数组 
		List<ProcessBean> list= (List<ProcessBean>)JSONArray.toCollection(jsonArray, ProcessBean.class);
		for(ProcessBean processBean:list) {
			this.updateProcessByCode(processBean, map);
		}
	}

	public void deleteAllProcess(String idArray) {
		JSONArray jsonArray = JSONArray.fromObject(idArray);
		List<String> idList=jsonArray.subList(0, jsonArray.size());
		procedureMapper.deleteAllProcess(idList);
	}

	public List<ProcessBean> getTableDate(Map map) {
		return procedureMapper.getTableDate(map);
	}

	public List<ProcessBean> addProcessByFile(MultipartFile filename, MyUser myUser) throws Exception {
		Date day=new Date();    
		SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); 
		List<ProcessBean> returnList=new ArrayList<ProcessBean>();
		String excelName = filename.getOriginalFilename();
		boolean suffixName = excelName.endsWith(".xlsx");
		if(!suffixName){
			throw new ServiceException("请按照模板上传xlsx格式文件");
		}
		List<ProcessBean> processList=new ArrayList<ProcessBean>();
		XSSFWorkbook xwb;
		xwb=new XSSFWorkbook(filename.getInputStream());
		XSSFSheet sheet = xwb.getSheetAt(0);
		int rowNum = sheet.getLastRowNum();//得到有效的行数
		int colNum = sheet.getRow(0).getLastCellNum();
		ProcessBean process;
		for (int rowIndex = 1; rowIndex < rowNum + 1; rowIndex++) {
			process=new ProcessBean();
			XSSFRow row=sheet.getRow(rowIndex);
			for(int cellIndex=0;cellIndex<colNum;cellIndex++){
				XSSFCell cell=row.getCell(cellIndex);
				switch(cellIndex){
				case 0:process.setProcessCode(cell.getStringCellValue().trim());break;
				case 1:process.setProductionLine(cell.getStringCellValue().trim());break;
				case 2:process.setWorkshopName(cell.getStringCellValue().trim());break;
				case 3:process.setProcessName(cell.getStringCellValue().trim());break;
				case 4:double x=0.0;
				       try {
				    	   x=cell.getNumericCellValue();
				       }catch(Exception e) {
				    	   x=Double.parseDouble(cell.getStringCellValue());
				       }
					process.setWorkingProcedureDuration(x);
					break;
				case 5:
					double xx=0.0;
				       try {
				    	   xx=cell.getNumericCellValue();
				       }catch(Exception e) {
				    	   xx=Double.parseDouble(cell.getStringCellValue());
				       }
					process.setSort(xx);break;
				case 6:process.setStatus(cell.getStringCellValue().trim());break;
				case 7:
					double xxx=0.0;
				       try {
				    	   xxx=cell.getNumericCellValue();
				       }catch(Exception e) {
				    	   xxx=Double.parseDouble(cell.getStringCellValue());
				       }
					process.setUnitPrice(xxx);break;
				case 8:process.setChargeUnit(cell.getStringCellValue().trim());break;
				}
				process.setCompany(myUser.getCompany());
				process.setCreater(myUser.getUserName());
				process.setCreationTime(df.format(day));
				process.setLastModifier(myUser.getUserName());
				process.setLastModifyTime(df.format(day));
			}
			//此处插入部门与车间？
			ProcessBean pro=procedureMapper.getProcessBean(process);
			if(null!=pro) {
				//已存在，修改
				pro.setLastModifier(myUser.getUserName());
				pro.setLastModifyTime(df.format(day));
				returnList.add(pro);
			}else {
				//不存在，添加
				processList.add(process);
			}
		}
		xwb.close();
		List<ProcessBean> childrenList=null;
		if(returnList.size()>0) {
			if(returnList.size()>50) {
				int count=(int) Math.floor(returnList.size()/50);
				for(int i=0;i<count;i++) {
					childrenList=returnList.subList(i*50, (i+1)*50);
					procedureMapper.updateProcessByFile(childrenList);
				}
				childrenList=returnList.subList(count*50, returnList.size());
				procedureMapper.updateProcessByFile(childrenList);
			}else {
				procedureMapper.updateProcessByFile(returnList);
			}
		}
		if(processList.size()>0) {
			if(processList.size()>50) {
				int count=(int) Math.floor(processList.size()/50);
				for(int i=0;i<count;i++) {
					childrenList=processList.subList(i*50, (i+1)*50);
					procedureMapper.addProcessByFile(childrenList);
				}
				childrenList=processList.subList(count*50, processList.size());
				procedureMapper.addProcessByFile(childrenList);
			}else {
				procedureMapper.addProcessByFile(processList);
			}
		}
		return returnList;
	}

	public Object getAllProcess(Map map) {
		List<ProcessBean> processBeans=procedureMapper.getProcessIdAndName(map.get("loginCompany").toString());
		return  processBeans;
	}

	/**
	 * 设置工序qc表
	 * @param processId 工序id
	 * @param QCDetailArray qc详情配置
	 * @return
	 * @throws ServiceException
	 */
	public String  setProcessQCTable(Map map) {
		StringUtil.checkIsTrue(map, "processId", "未获取到工序id");
		StringUtil.checkIsTrue(map, "QCDetailArray", "未获取到参数");
		StringUtil.checkIsTrue(map, "QCDetailArray", "未获取到参数");
		String QCDetailArray= map.get("QCDetailArray").toString();
		JSONArray jsonArray = JSONArray.fromObject(QCDetailArray);
		List<QCProcessBean> list=(List<QCProcessBean>) JSONArray.toCollection(jsonArray, QCProcessBean.class);
		int  deleteRow=procedureMapper.deleteQCTableByProcessId(map);
		map.put("list", list);
		int addRow = procedureMapper.addQCTable(map);
		int  updateRow = procedureMapper.updateQCTime(map);
		return ReturnStringUtil.SET_SUCCESS;
	}

	/**
	 * 通过工序获取qc配置
	 * processId 工序id
	 * @param map
	 * @return
	 */
	public List<BaseProcessDetailPojo> getProcessQCTableByProcessId(Map map) {
		StringUtil.checkIsTrue(map, "type", "未获取到类型参数");
		StringUtil.checkIsTrue(map, "processId", "未获取到工序id");
	    int type = Integer.parseInt(map.get("type").toString());
	    List<BaseProcessDetailPojo> list=null;
	    if(type == 1) {
	    	StringUtil.checkIsTrue(map, "orderId", "未获取到订单编号");
	    	Integer qcReportId= procedureMapper.getLastTypeQCReport(map);//获取该类型的最后一次报工
	    	if(null==qcReportId || qcReportId.equals(0)) {
	    		list = procedureMapper.getProcessQCTableByProcessId(map);
	    	}else {
	    		map.put("qcReportId", qcReportId);
	    		list = procedureMapper.getFirstQCValueById(map);
	    	}
	    }else {
	    	list = procedureMapper.getProcessQCTableByProcessId(map);
	    }
		return list;
	}

	/**
	 * qc报工
	 * @param map
	 * @return
	 * @throws ParseException 
	 */
	public String qcReport(Map map) throws ParseException {
		StringUtil.checkIsTrue(map, "jsonObject", "未获取到参数");
		String jsonObject=map.get("jsonObject").toString();
	    JSONObject jsonObj = JSONObject.fromObject(jsonObject);    
        Map<String, Class> classMap = new HashMap<String, Class>();    
        classMap.put("detail", QCReportDetailBean.class);      
        QCReportBean qcReportBean = (QCReportBean) JSONObject.toBean(jsonObj,QCReportBean.class, classMap);
        this.setIntervalTime(map,qcReportBean);
        map.put("qcReport", qcReportBean);
        int mainRow=procedureMapper.insertQCMain(map);
        Assert.isTrue(mainRow>0,ReturnStringUtil.ADD_ERROR);
        int detailRow=procedureMapper.insertQCDetail(map);
        Assert.isTrue(detailRow>0,ReturnStringUtil.ADD_ERROR);
        //以下为审核消息
        List<String> openIdList=this.getPeocessApprovalUser(qcReportBean.getProcessId());
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
        String dayTime = simpleDateFormat.format(new Date());
        String neiRong="QC人:"+map.get("loginUserName").toString()+"\n"+"工序名称:"+qcReportBean.getProcessName();
        for(String openId:openIdList) {
        	String msgString=this.sendMessage("有新的qc记录需要审核，请尽快审核", "qc审核", map.get("loginUserName").toString(), map.get("loginUserPhone").toString(), dayTime, neiRong,RedirectUrlUtil.QC_REPORT_APPROVAL+"?id="+map.get("mainId").toString(),openId);
        }
		return ReturnStringUtil.REPORT_SUCCESS; 
	}

	
	/**
	 *  获取工序审核人的openId
	 * @param processId 工序id
	 * @return
	 */
	private List<String> getPeocessApprovalUser(Integer processId) {
		List<String> userIdList=procedureMapper.getProcessApprovelUserIdByProcessId(processId);
		List<String> openIdList = null;
		if(userIdList.size()<=0) {
			 openIdList = new ArrayList<String>(); 
		}else {
			Map map=new HashMap();
			map.put("userIds", userIdList);
			openIdList=weiXinPeopleService.getOpenIdByUserIds(map);
		}
		return openIdList;
	}

	/**
	 * 发送消息申请
	 * @return
	 */
	private  String sendMessage(String title,String type,String userName,String phone,String time,String neiRong,String pageType,String openId) {
		boolean bool=false;
		String accessToken=weiXinService.getAccessToken(null); 
		com.alibaba.fastjson.JSONObject json=WeixinTemplateList.packJsonWatiApproval(title, type, userName,phone,time,neiRong , null, null, null, null, null, null, null, null);
		String xx=WeixinTemplateSender.sendWechatmsgToUser(openId, WeiXinParamesUtil.watiApprovalTemplateID, WeiXinParamesUtil.messageLink+"?loginToken="+openId+"&pageType="+pageType, json, accessToken);
		if(!"success".equals(xx)) {
			bool=true;
		}
		return "";
		
	}
	
	/**
	 * 设置时间间隔
	 * @param map
	 * @param qcReportBean 
	 * @throws ParseException 
	 */
	private void setIntervalTime(Map map, QCReportBean qcReportBean) throws ParseException {
		if(1==qcReportBean.getType()) {
			return ;
		}
		SimpleDateFormat simpleDateFormat=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		String nowTime=simpleDateFormat.format(new Date());
		Map mapParam=new HashMap();
		mapParam.put("loginCompany", map.get("loginCompany"));
		mapParam.put("loginUserId", map.get("loginUserId"));
		mapParam.put("orderId", qcReportBean.getOrderId());
		mapParam.put("processId", qcReportBean.getProcessId());
		List<QCReportBean> list  =  procedureMapper.getQCDisplay(mapParam);
		if(list.size()<=0) {
			return ;
		}
		List<QCReportBean> typeList = list.stream().filter(ss->ss.getType().equals(qcReportBean.getType()) && ss.getCreateUser().equals(map.get("loginUserId").toString())).collect(Collectors.toList());
		/**
		 * 如果之前从来没有过此类型的qc
		 */
		if(typeList.size()<=0) {
			/**
			 * 首检
			 */
			List<QCReportBean> firstList=list.stream().filter(ss->ss.getType() == 1 ).collect(Collectors.toList());
		    //如果没有首检，时间从出现在开始算空缺时间为0
			if(firstList.size()<=0) {
		    	qcReportBean.setIntervalTime(0.0);	
		    }else {
		    	Double intervalTime =this.getIntervalTimeBySDtime(firstList.get(0).getCreateTime(),nowTime, map.get("loginCompany").toString(), map.get("loginUserId").toString());
		    	Assert.isTrue(intervalTime>3,"间隔时间不能小于三分钟");
		    	qcReportBean.setIntervalTime(intervalTime);
		    }
		}else {
			Double intervalTime =this.getIntervalTimeBySDtime(typeList.get(0).getCreateTime(),nowTime, map.get("loginCompany").toString(), map.get("loginUserId").toString());
			Assert.isTrue(intervalTime>3,"间隔时间不能小于三分钟");
			qcReportBean.setIntervalTime(intervalTime);
		}
	}

	/**
	 * 
	 * @param personId 
	 * @param company 
	 * @param createTime
	 * @param nowTime
	 * @return
	 * @throws ParseException 
	 */
	private Double getIntervalTimeBySDtime(String startDate, String endDate, String company, String personId) throws ParseException {
		SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		Map map=new HashMap();
		map.put("loginCompany", company);
		map.put("personId", personId);
		map.put("startDate", startDate);
		map.put("endDate", endDate);
		//获取排班与工资设定信息
		List<AttendPlanAndFinanceDetailPojo> planAndFinanceDetailPojos = attendanceMapper.getAttendPlanAndFinanceDetail(map);
		//获取时间间隔多少分钟
		Double btnMinute=this.getMinuteByBetweenTime(startDate,endDate);
		if(planAndFinanceDetailPojos.size()<=0) {//没有设置考勤时间一律当做全天二十四小时上班处理
			return btnMinute;
		}else if(planAndFinanceDetailPojos.get(0).getWorkdateList() == null || planAndFinanceDetailPojos.get(0).getWorkdateList().size()<=0){
			return btnMinute;
		}else {
			//工作日期
			List<Map<String, Object>> workdateList=planAndFinanceDetailPojos.get(0).getWorkdateList();
			Double intervalTime = 0.0;
			String startDay = startDate.substring(0, 11);
			String endDay = endDate.substring(0, 11);
			String startTime = startDate.substring(11, 16);
			String endTime = endDate.substring(11, 16);
			//开始和结束是同一天
			if(startDay.equals(endDay)) {
				List<String> workTimeList=(List<String>) workdateList.get(0).get("clock");
				if(workTimeList.size()<=0) {
					intervalTime=btnMinute;
				}else {
					List<String> betweenList=new ArrayList();
					//判断是否加头
					int x=0;
					for(int j=workTimeList.size()-1;j>=0;j--) {
						String str=workTimeList.get(j);
						//获取比开始时间更玩的应打卡时间
						if((startDay+startTime).compareTo(startDay+str) < 0) {
							x=x+1;
						}
					}
					if(x%2!=0) {
						betweenList.add(startTime);
					}
					/**
					 * 两者中间的结果
					 */
					for(int j=workTimeList.size()-1;j>=0;j--) {
						String str=workTimeList.get(j);
						//获取比开始时间更玩的应打卡时间
						if((startDay+startTime).compareTo(startDay+str) < 0 && (endDay+endTime).compareTo(endDay+str) > 0) {
							betweenList.add(str);
						}
					}
					/**
					 * 判断是否加尾
					 */
					x=0;
					for(int j=0;j<workTimeList.size();j++) {
						String str=workTimeList.get(j);
						//获取比开始时间更玩的应打卡时间
						if((endDay+endTime).compareTo(endDay+str) > 0) {
							x=x+1;
						}
					}
					if(x%2!=0) {
						betweenList.add(endTime);
					}
					intervalTime = this.getManurByArray(betweenList);
				}
			}else {
				for(int i=0;i<workdateList.size();i++) {
					Map<String,Object> onDayMap=workdateList.get(i);
					List<String> workTimeList= (List<String>) onDayMap.get("clock");
					if(workTimeList.size()<=0) {
						continue;
					}
					if(startDay.equals(onDayMap.get("workdate")+" ")) {//如果是开始日期
						List<String> afterList=new ArrayList();
						for(int j=workTimeList.size()-1;j>=0;j--) {
							String str=workTimeList.get(j);
							//获取比开始时间更玩的应打卡时间
							if((startDay+startTime).compareTo(startDay+str) < 0) {
								afterList.add(str);
							}
						}
						//如果不在打卡时间范围
						if(afterList.size()==0) {
							continue;
						}
						//如果
						if(afterList.size()%2!=0) {
							afterList.add(startTime);
						}
						double min=this.getManurByArray(afterList);
						intervalTime=intervalTime+min;
					}else if(endDay.equals(onDayMap.get("workdate")+" ")) {//如果是结束日期
						List<String> beforeList=new ArrayList();
						for(int j=0;j<workTimeList.size();j++) {
							String str=workTimeList.get(j);
							//获取比开始时间更玩的应打卡时间
							if((endDay+endTime).compareTo(endDay+str) > 0) {
								beforeList.add(str);
							}
						}
						//如果不在打卡时间范围
						if(beforeList.size()==0) {
							continue;
						}
						//如果
						if(beforeList.size()%2!=0) {
							beforeList.add(endTime);
						}
						double min=this.getManurByArray(beforeList);
						intervalTime=intervalTime+min;
					}else {//如果是中间日期
						double min=this.getManurByArray(workTimeList);
						intervalTime=intervalTime+min;
					}
				}
			}
			return intervalTime;
		} 
	}

	/**
	 * 通过数组获取间隔时间
	 * @param workTimeList
	 * @return
	 * @throws ParseException 
	 */
	private double getManurByArray(List<String> workTimeList) throws ParseException {
		workTimeList.sort(Comparator.naturalOrder());
		String fixedDay="2019-11-14 ";
		List<List<String>> splitList=this.getSplitList(2,workTimeList); 
		double min=0.0;
		for(int j=0;j<splitList.size();j++) {
			List stageList=splitList.get(j);
			min=min+this.getMinuteByBetweenTime(fixedDay+stageList.get(0)+":00",fixedDay+stageList.get(1)+":00");
		}
		return min;
	}

	/**
	 * 将数组分割横同样长度的数组
	 * @param splitNum 分割后每个数组的长度
	 * @param list
	 * @return
	 */
	private List<List<String>> getSplitList(int splitNum, List<String> list) {
	    List<List<String>> splitList = new ArrayList<>();
	    int groupFlag = list.size() % splitNum == 0 ? (list.size() / splitNum) : (list.size() / splitNum + 1);
	    for (int j = 0; j < groupFlag; j++) {
	      if ((j * splitNum + splitNum) <= list.size()) {
	        splitList.add(list.subList(j * splitNum, j * splitNum + splitNum));
	      } else if ((j * splitNum + splitNum) > list.size()) {
	        splitList.add(list.subList(j * splitNum, list.size()));
	      } else if (list.size() < splitNum) {
	        splitList.add(list.subList(0, list.size()));
	      }
	    }
	    return splitList;
	  }
	
	
	
	
	/**
	 * 获取两个时间间隔分钟数
	 * @param startDate 开始时间
	 * @param endDate 结束时间
	 * @throws ParseException 
	 */
	private Double getMinuteByBetweenTime(String startDate, String endDate) throws ParseException {
		//时间处理类
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        long endTime =df.parse(endDate).getTime();
        //从对象中拿到时间
        long startTime = df.parse(startDate).getTime();
        long diff=(endTime-startTime)/1000/60;
        return (double) diff;
	}

	/**
	 * 获取qc报工内容
	 * companyOrderId 公司订单编号
	 * factoryId 工厂型号
	 * customerId 客户型号
	 * processId 工序id
	 * createUser qc人
	 * startTime 开始时间
	 * endTime 结束时间
	 * status 状态
	 * result 通过不通过
	 * @param request
	 * @return
	 */
	public DatatablesViewPageBean<QCReportBean> getQcReportData(Map map) {
		DatatablesViewPageBean<QCReportBean> datatablesViewPageBean=new DatatablesViewPageBean<QCReportBean>();
		int count=procedureMapper.getQcReportDataCount(map);
		List<Integer> idList=procedureMapper.getQCIdList(map);
		List<QCReportBean> list= null;
		if(idList.size()>0) {
			map.put("idList", idList);
			list=procedureMapper.getQcReportData(map);
		}
		datatablesViewPageBean.setReturnData(list);
		datatablesViewPageBean.setiTotalDisplayRecords(count);
		datatablesViewPageBean.setiTotalRecords(count);
		return datatablesViewPageBean;
	}
	

	/**
	 * 查询自己的报工记录
	 * @param map
	 * @return
	 */
	public DatatablesViewPageBean<QCReportBean> getQcReportDataSelf(Map map) {
		map.put("createUser", map.get("loginUserId"));
		return this.getQcReportData(map);
	}
	
	/**
	 * 查询可审核的报工记录
	 * @param map
	 * @return
	 */
	public DatatablesViewPageBean<QCReportBean> getQcReportDataApproval(Map map) {
		List<String> processId=procedureMapper.getSelfCanApprovalProcessId(map);
		map.put("processIdList", processId);
		return this.getQcReportData(map);
	}
	
	
	
	
	/**
	 * 审核qc报工
	 * idArray id数组
	 * suatus
	 * @param map
	 * @return
	 */
	public String approvalQCReport(Map map) {
		StringUtil.checkIsTrue(map, "idArray", "未获取到id");
		StringUtil.checkIsTrue(map, "status", "未获取到状态");
		String idArray=map.get("idArray").toString();
		JSONArray jsonArray = JSONArray.fromObject(idArray);
		List<Integer> idList=jsonArray.subList(0, jsonArray.size());
		Assert.isTrue(idList.size()>0,"未获取到id");
		map.put("idList", idList);
		List<QCReportBean> list=procedureMapper.getQcReportData(map);
		List<QCReportBean> aleradyApprovalList=list.stream().filter(pp->pp.getStatus()!=0).collect(Collectors.toList());
		Assert.isTrue(aleradyApprovalList.size()<=0,ReturnStringUtil.APPROVAL_ALREADY_EXCEPTION);
		int  row=procedureMapper.approvalQCReport(map);
		Assert.isTrue(row>0,ReturnStringUtil.OPERATION_ERROR);
		Integer status= Integer.parseInt(map.get("status").toString()) ;
		//发消息
		for(QCReportBean qc:list) {
			workshopService.sendApprovalStatusMassage(status, qc.getCreateUserId()+"", map.get("loginUserName").toString(), "您的qc申请被通过", RedirectUrlUtil.QC_REPORT_APPROVAL+"?id="+qc.getId());
		}
		return ReturnStringUtil.APPROVAL_SUCCESS;
	}

	/**
	 * 获取QC看板数据
	 * @param map
	 * @return
	 */
	public List<QCReportBean> getQCDisplay(Map map) {
	   List<QCReportBean> list=procedureMapper.getQCDisplay(map);
	   if(list.size()>0) {
		   Set<String> orderIdSet=list.stream().map(QCReportBean::getOrderId).collect(Collectors.toSet());
		   Set<Integer> processIdSet=list.stream().map(QCReportBean::getProcessId).collect(Collectors.toSet());
		   map.put("orderIdSet", orderIdSet);
		   map.put("processIdSet", processIdSet);
		   List<QCReportBean> reportList=procedureMapper.getReportDetail(map);
		   list.addAll(reportList);
	   }
	   return list;
	}

	
	
	/**
	 * 提醒定时器
	 */
	public void remindTimeing() {
		  
	}
}










